# -*- coding: utf-8 -*-
# @Time: 2022/9/9 19:40
# @File: main.py
import sys
import pygame
from setting import *
from bird import Bird
from pipe import Pipe


# 初始化设置
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Fly Bird")
clock = pygame.time.Clock()

# Group和Sprite的初始化
pipe_sprites = pygame.sprite.Group()
bird = Bird(pipe_sprites)
Pipe(pipe_sprites)

# 主循环逻辑
pipe_time_interval = 0
has_dead = False
while True:
    # 程序退出判断
    if any(event.type == pygame.QUIT for event in pygame.event.get()):
        pygame.quit()  # pygame退出
        sys.exit()  # 程序正常退出

    duration_time = clock.tick_busy_loop() / 1000  # 转换单位为：秒

    # 绘制背景
    pygame.draw.rect(screen, SCREEN_BACKGROUND, screen.get_rect())

    if bird.alive:
        pipe_time_interval += duration_time  # 间隔时长
    else:
        pipe_time_interval = 0
    if pipe_time_interval >= PIPE_TIME_INTERVAL:
        pipe_time_interval = 0
        Pipe(pipe_sprites)  # 间隔一段时间生成新的水管

    if not bird.alive:
        has_dead = True
    # 复活后重置水管
    if bird.alive and has_dead:
        has_dead = False
        pipe_sprites.empty()
        Pipe(pipe_sprites)

    # 鸟和水管的更新
    bird.update(duration_time)
    pipe_sprites.update(duration_time, bird.alive)

    pygame.display.update()  # 显示界面更新
